package com.youoor.mvc;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.youoor.common.IdWorker;
import com.youoor.domain.CardFavo;
import com.youoor.domain.CardLink;
import com.youoor.domain.UserCard;
import com.youoor.domain.UserInfo;
import com.youoor.dto.CardInfo;
import com.youoor.dto.RetDTO;
import com.youoor.enums.ErrorCodeEnum;
import com.youoor.exception.ServiceException;
import com.youoor.interceptors.RequestAttribute;
import com.youoor.service.CardFavoService;
import com.youoor.service.CardLinkService;
import com.youoor.service.UserCardService;

@Controller
@RequestMapping(value = { "/open", "/core", "/inner" }, produces = "application/json")
public class CardController extends AbstractController{

	private static final Logger logger = LoggerFactory.getLogger(CardController.class);
	
	@Autowired
	private UserCardService userCardService;
	
	@Autowired
	private CardLinkService cardLinkService;
	
	@Autowired
	private CardFavoService cardFavoService;
	
	
	

	
	@RequestMapping("/getCardInfoByUserId")
	public RetDTO getCardInfoByUserId() {
		UserInfo userInfo = (UserInfo) httpSession.getAttribute("loginUser");
		Integer userId = userInfo.getUserId();
		UserCard userCard = userCardService.getUserCardByUserId(userId);
		CardInfo cardInfo = new CardInfo();
		if (userCard != null) {
			List<CardLink> links = cardLinkService.getLinksByCardId(userCard.getCardId());
			cardInfo.setUserCard(userCard);
			cardInfo.setLinks(links);
		}
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("cardInfo", cardInfo);
		retDTO.markSuccess();
		return retDTO;
	}
	
	@RequestMapping("/getCardInfoByCardId")
	public RetDTO getCardInfoByCardId(@RequestParam("cardId") String cardId) {
		UserCard userCard = userCardService.selectByPrimaryKey(Integer.valueOf(cardId));
		CardInfo cardInfo = new CardInfo();
		if (userCard != null) {
			List<CardLink> links = cardLinkService.getLinksByCardId(userCard.getCardId());
			cardInfo.setUserCard(userCard);
			cardInfo.setLinks(links);
		}
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("cardInfo", cardInfo);
		retDTO.markSuccess();
		return retDTO;
	}
	
	
	@RequestMapping("/createCard")
	public RetDTO createCard(@RequestParam("name") String name,
						   @RequestParam("occupation") String occupation,
						   @RequestParam("location") String location,
						   @RequestParam("description") String description,
						   @RequestParam("links") List<String> links) {
		UserInfo userInfo = (UserInfo) httpSession.getAttribute("loginUser");
		Integer userId = userInfo.getUserId();
		UserCard userCard = new UserCard();
		userCard.setUserId(userId);
		userCard.setName(name);
		userCard.setOccupation(occupation);
		userCard.setLocation(location);
		userCard.setDescription(description);
		List<CardLink> cardLinks = new ArrayList<CardLink>();
		if (links != null && links.size() > 0) {
			for (String link:links) {
				CardLink cardLink = new CardLink();
				cardLink.setCardId(userCard.getCardId());
				cardLink.setLinkId(idWorker.nextId());
				cardLink.setLinkUrl(link);
			}
		}
		Integer cardId = userCardService.createCard(userCard, cardLinks);
		
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("cardId", cardId);
		retDTO.markSuccess();
		return retDTO;
	}
	
	@RequestMapping("/addviewCount")
	public RetDTO addviewCount(@RequestAttribute("cardId") String cardId) {
		UserCard userCard = userCardService.selectByPrimaryKey(Integer.valueOf(cardId));
		userCard.setViewCount(userCard.getViewCount()+1);
		userCardService.updateByPrimaryKey(userCard);
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("result", "ok");
		retDTO.markSuccess();
		return retDTO;
	}
	
	@RequestMapping("/setXY")
	public RetDTO setXY(@RequestAttribute("type") String type,
			@RequestAttribute("iX") String iX,
			@RequestAttribute("iY") String iY) {
		UserCard userCard = getUserCard();
		//UserCard newUserCard = new UserCard();
		//newUserCard.setCardId(userCard.getCardId());
		userCard.setUtime(new Date());
		if("card".equals(type)) {
			userCard.setCardX(Integer.valueOf(iX));
			userCard.setCardY(Integer.valueOf(iY));
		}else {
			userCard.setViewX(Integer.valueOf(iX));
			userCard.setViewY(Integer.valueOf(iY));
		}
		userCardService.updateByPrimaryKeySelective(userCard);
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("result", "ok");
		retDTO.markSuccess();
		return retDTO;
	}
	
	@RequestMapping("/editCard")
	public RetDTO editCard(@RequestAttribute("cardId") String cardId,
			@RequestAttribute("name") String name,
			@RequestAttribute("hobby") String hobby,
			@RequestAttribute("occupation") String occupation,
			@RequestAttribute("location") String location,
			@RequestAttribute("description") String description,
			@RequestAttribute("links") String links,
			@RequestAttribute("styleInt") String styleInt,
			@RequestAttribute("background") String background) {
		UserInfo userInfo = (UserInfo) httpSession.getAttribute("loginUser");
		Integer userId = userInfo.getUserId();
		UserCard userCard = userCardService.getUserCardByUserId(userId);
		if (userCard == null) {
			userCard = new UserCard();
		}
		Date nowTime = new Date();
		userCard.setUserId(userId);
		userCard.setName(name);
		userCard.setHobby(hobby);
		userCard.setOccupation(occupation);
		userCard.setLocation(location);
		userCard.setDescription(description);
		userCard.setBackground(background);
		userCard.setStyleInt(Integer.valueOf(styleInt));
		userCard.setCtime(nowTime);
		userCard.setUtime(nowTime);
		List<CardLink> cardLinks = new ArrayList<CardLink>();
		if (!StringUtils.isEmpty(links)) {
			String[] linkArr =links.split(",");
				for (int k = 0;k<linkArr.length;k++) {
				CardLink cardLink = new CardLink();
				cardLink.setCardId(userCard.getCardId());
				cardLink.setLinkId(idWorker.nextId());
				cardLink.setLinkUrl(linkArr[k]);
				cardLink.setCtime(nowTime);
				cardLink.setUtime(nowTime);
				cardLinks.add(cardLink);
			}
		}
		if (userCard.getCardId() == null) {
			userCardService.createCard(userCard, cardLinks);
		}else {
			List<CardLink> existLinks = cardLinkService.getLinksByCardId(userCard.getCardId());
			userCardService.editCard(userCard, cardLinks);
			if (!CollectionUtils.isEmpty(existLinks)) {
				for (CardLink link:existLinks) {
					cardLinkService.deleteByPrimaryKey(link.getLinkId());
				}
			}
		}
		httpSession.setAttribute("userCard", userCard);
		
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("result", "ok");
		retDTO.markSuccess();
		return retDTO;
	}
	
	
	/**
	 * 
	 * @param type 发现  最新，最热
	 * @return
	 */
	@RequestMapping("/getDiscoverList")
	public RetDTO getDiscoverList(@RequestParam("type") String type,
			@RequestAttribute("cardId") String cardId,
			@RequestAttribute("num") String num) {
		List<UserCard> cardList = userCardService.getLatestList(Integer.valueOf(cardId),Integer.valueOf(num));
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("cardList", cardList);
		retDTO.markSuccess();
		return retDTO;
	}
	
	/**
	 * 
	 * @param type 推荐 最新，最热
	 * @return
	 */
	@RequestMapping("/getRecommendList")
	public RetDTO getRecommendList(@RequestParam("type") String type,
			@RequestAttribute("cardId") String cardId,
			@RequestAttribute("num") String num) {
		List<UserCard> cardList = userCardService.getLatestList(Integer.valueOf(cardId),Integer.valueOf(num));
		
		List<CardInfo>  infoList = new ArrayList<CardInfo>();
		if (!CollectionUtils.isEmpty(cardList)) {
			for (UserCard userCard: cardList) {
				CardInfo cardInfo = new CardInfo();
				List<CardLink> links = cardLinkService.getLinksByCardId(userCard.getCardId());
				cardInfo.setUserCard(userCard);
				cardInfo.setLinks(links);
				infoList.add(cardInfo);
			}
		}
		
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("infoList", infoList);
		retDTO.markSuccess();
		return retDTO;
	}
	
	/**
	 * 收藏卡片
	 * @param favoUserId
	 * @return
	 */
	@RequestMapping("/favoCard")
	public RetDTO favoCard(@RequestAttribute("cardId") String cardId) {
		UserCard userCard = getUserCard();
		if (Integer.valueOf(cardId)==userCard.getCardId()) {
			throw new ServiceException(ErrorCodeEnum.CODE_YOUOOR_VERIFY_NOT_FAVOE_SELF);
		}
		if(cardFavoService.verifyFavo(Integer.valueOf(cardId), userCard.getCardId())!= null) {
			throw new ServiceException(ErrorCodeEnum.CODE_YOUOOR_VERIFY_FAVOED);
		}
		cardFavoService.insertCardFavo(Integer.valueOf(cardId), userCard.getCardId());
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("result", "ok");
		retDTO.markSuccess();
		return retDTO;
	}
	
	/**
	 * 取消收藏
	 * @param cardId
	 * @return
	 */
	@RequestMapping("/cancelFavoCard")
	public RetDTO cancelFavoCard(@RequestAttribute("cardId") String cardId) {
		UserCard userCard = getUserCard();
		CardFavo cardFavo = cardFavoService.verifyFavo(Integer.valueOf(cardId), userCard.getCardId());
		if (cardFavo != null) {
			cardFavoService.deleteByPrimaryKey(cardFavo.getFavoId());
		}
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("result", "ok");
		retDTO.markSuccess();
		return retDTO;
	}
	
	/**
	 * 获取收藏列表(我收藏的)
	 * @return
	 */
	@RequestMapping("/getFavoList")
	public RetDTO getFavoList(@RequestAttribute("pageIndex") String pageIndex,
			@RequestAttribute("num") String num) {
		UserCard userCard = getUserCard();
		List<CardFavo> cardFavoList = cardFavoService.getFavoList(userCard.getCardId(),Integer.valueOf(pageIndex),Integer.valueOf(num));
		List<CardInfo>  infoList = new ArrayList<CardInfo>();
		if(!CollectionUtils.isEmpty(cardFavoList)) {
			for (CardFavo cardFavo:cardFavoList) {
				UserCard userCard1 = userCardService.selectByPrimaryKey(cardFavo.getCardId());
				CardInfo cardInfo = new CardInfo();
				List<CardLink> links = cardLinkService.getLinksByCardId(userCard1.getCardId());
				cardInfo.setUserCard(userCard1);
				cardInfo.setLinks(links);
				infoList.add(cardInfo);
			}
		}
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("infoList",infoList);
		retDTO.markSuccess();
		return retDTO;
	}
	
	/**
	 * 获取收藏我的列表
	 * @return
	 */
	@RequestMapping("/getFavoListToMe")
	public RetDTO getFavoListToMe(@RequestAttribute("favoId") String favoId,
			@RequestAttribute("num") String num) {
		UserCard userCardMe = getUserCard();
		List<CardFavo> cardFavoList =  cardFavoService.getFavoListToMe(Integer.valueOf(userCardMe.getCardId()),Long.valueOf(favoId),Integer.valueOf(num));
		List<CardInfo>  infoList = new ArrayList<CardInfo>();
		if(!CollectionUtils.isEmpty(cardFavoList)) {
			for (CardFavo cardFavo:cardFavoList) {
				UserCard userCard = userCardService.selectByPrimaryKey(cardFavo.getCardId());
				CardInfo cardInfo = new CardInfo();
				List<CardLink> links = cardLinkService.getLinksByCardId(userCard.getCardId());
				cardInfo.setUserCard(userCard);
				cardInfo.setLinks(links);
				infoList.add(cardInfo);
			}
		}
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("infoList",infoList);
		retDTO.markSuccess();
		return retDTO;
	}
	
	/**
	 * 
	 * @param num
	 * @return
	 */
	@RequestMapping("/getViewCard")
	public RetDTO getViewCard(@RequestAttribute("pageIndex") String pageIndex,@RequestAttribute("limit") String limit) {
		List<UserCard> viewCardList = userCardService.getUserCardForView(Integer.valueOf(pageIndex), Integer.valueOf(limit));
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("viewCardList",viewCardList);
		retDTO.markSuccess();
		return retDTO;
	}
	
	/**
	 * 
	 * @param num
	 * @return
	 */
	@RequestMapping("/getViewRecommendCard")
	public RetDTO getViewRecommendCard(@RequestAttribute("limit") String limit) {
		List<UserCard> viewCardList = userCardService.getUserRecommendCardForView(Integer.valueOf(limit));
		List<CardInfo>  infoList = new ArrayList<CardInfo>();
		if(!CollectionUtils.isEmpty(viewCardList)) {
			for (UserCard userCard:viewCardList) {
				CardInfo cardInfo = new CardInfo();
				List<CardLink> links = cardLinkService.getLinksByCardId(userCard.getCardId());
				cardInfo.setUserCard(userCard);
				cardInfo.setLinks(links);
				infoList.add(cardInfo);
			}
		}
		RetDTO retDTO = new RetDTO();
		retDTO.addResult("infoList",infoList);
		retDTO.markSuccess();
		return retDTO;
	}
	
	
	
}
